package cn.tangsihai.hrm.config;

import cn.tangsihai.hrm.handler.MyAuthenticationFailureHandler;
import cn.tangsihai.hrm.handler.MyAuthenticationSuccessHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * 认证过滤器：用来过滤所有认证的操作，认证成功或者失败都有相应的处理
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)  //开启方法授权
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
    //配置认证管理器，授权模式为“poassword”时会用到
    @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    // BCryptPasswordEncoder密码编码器：加密，比md5更强大，无法被暴力破解
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    //授权规则配置
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests() //授权配置
                // 登录路径放行：不需要登录就可以操作的资源放行
                .antMatchers("/login/user", "/login/saveLoginAndMeal", "/login/saveLogin").permitAll()
                .anyRequest().authenticated() //其他路径都要认证之后才能访问
                .and().formLogin() //允许表单登录
                .successHandler(new MyAuthenticationSuccessHandler()) // 认证成功处理程序
                .failureHandler(new MyAuthenticationFailureHandler()) // 认证失败处理程序
                .and().logout().permitAll() //登出路径放行 /logout
                .and().csrf().disable(); //关闭跨域伪造检查
    }
}